import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import './model/cus_dialog.dart';
import './user_proof.dart';

class Utils {
  static request({@required BuildContext context, @required String method, @required String url, @required Map data, Function success, VoidCallback finnaly}) {
    if(success == null) {
      success = (){};
    }
    if(finnaly == null) {
      finnaly = (){};
    }
    var httpObj;
    if(method == 'POST') {
      httpObj = http.post(url, body: data);
    }else {
      if(null != data && data.keys.length > 0) {
        String reqStr = '';
        data.forEach((key, val) {
          reqStr += '&' + key + '=' + val.toString();
        });
        httpObj = http.get(url + (url.indexOf('?')==-1?'?':'&')+reqStr.substring(1));
      }else {
        httpObj = http.get(url);
      }
    }
    try {
      
      httpObj.then((response){
        Map responseJson;
        try {
          responseJson = json.decode(response.body);
        } catch (e) {
        }
        if(responseJson !=null && responseJson['s'] == 1) {
          success(responseJson);
        }else {
          CusDialog.showError(context, responseJson != null && responseJson['m']!=null && responseJson['m']!='' ? responseJson['m'] : '未知错误');
        }
      },onError: (error){
        CusDialog.showError(context, '服务器错误');
      }).whenComplete(finnaly);
    }catch (e) {
      finnaly();
      CusDialog.showError(context, '服务器错误');
    }
  }
  static post({@required BuildContext context, @required String url, @required Map data, Function success, VoidCallback finnaly}) {
    request(context:context, method: 'POST', url: url, data: data, success: success, finnaly: finnaly);
  }
  static verifyPost({@required BuildContext context, @required String url, @required Map data, Function success, VoidCallback finnaly}) {
    String userId = UserProof.userId;
    if(userId != '') {
      data['user_id'] = UserProof.userId;
      request(context:context, method: 'POST', url: url, data: data, success: success, finnaly: finnaly);
    }else {
      print('无user_id');
    }
  }
  static get({@required BuildContext context, @required String url, @required Map data, Function success, VoidCallback finnaly}) {
    request(context:context, method: 'GET', url: url, data: data, success: success, finnaly: finnaly);
  }
  static String formatDatetime(DateTime dateTime) {
    return "${dateTime.year}/${dateTime.month}/${dateTime.day} ${dateTime.hour}:${dateTime.minute}:${dateTime.second}";
  }
}